<template>
  <!-- 根据 formItem 的 mutable 属性决定显示选择框还是文本 -->
  <el-select-v2
    v-if="isMutable"
    v-bind="formItem.props"
    v-model="modelRef[formItem.key]"
    :options="formItemOptions"
  >
  </el-select-v2>
  <span v-else>{{ text }}</span>
</template>
<script setup lang="ts">
import { isArray } from 'node_modules/element-plus/es/utils'
import { computed, defineProps, PropType, toRefs } from 'vue'
// 定义组件属性
const props = defineProps({
  // 透传至 Form 的用户数据
  model: {
    type: Object as PropType<Record<string, any>>,
    default: () => ({})
  },
  // formItem 的表单配置
  formItem: {
    type: Object as PropType<{
      key: string;
      mutable?: boolean;
      props?: Record<string, any>;
      ext?: {
        options: Array<Record<string, any>>;
        resetKeys?: {
          value: string;
          label: string;
        };
      };
    }>,
    default: () => ({})
  }
})
// 使用 toRefs 解构 props 中的 model，避免直接修改 props
const { model } = toRefs(props)
const modelRef: any = model
// 计算是否可编辑
const isMutable = computed(() =>
  props.formItem.mutable === undefined ? true : props.formItem.mutable
)
// 获取选项的值
const getOptionValue = (option: Record<string, any>) => {
  const resetKeys = props.formItem.ext?.resetKeys
  return resetKeys ? option[resetKeys.value] : option.value
}
// 获取选项的标签
const getOptionLabel = (option: Record<string, any>) => {
  const resetKeys = props.formItem.ext?.resetKeys
  return resetKeys ? option[resetKeys.label] : option.label
}
// 获取选项列表
const formItemOptions = computed(() => {
  const options = props.formItem.ext?.options
  if (options) {
    options.map(option => {
      option.label = getOptionLabel(option)
      option.value = getOptionValue(option)
    })
    return options
  }
  return []
})
// 获取显示的文本
const text = computed(() => {
  if (Array.isArray(modelRef.value[props.formItem.key])) {
    const selectedOptions = formItemOptions.value.filter(
      option => {
        return modelRef.value[props.formItem.key].includes(getOptionValue(option))
      }
    ).map(e => getOptionLabel(e))
    return selectedOptions.length ? selectedOptions.join('、') : ''
  }
  const selectedOption = formItemOptions.value.find(
    option => {
      return getOptionValue(option) == modelRef.value[props.formItem.key]
    }
  )
  return selectedOption ? getOptionLabel(selectedOption) : ''
})
</script>
